<?php

namespace app\api\model;

use frame\app\Model;
use frame\lib\Db;

class Good extends Model
{
    public static function buy($param)
    {
        $good_name = $param['good_name'];
        if ($param['stock'] <= 0) error("<$good_name> 商品库存不足");
        $uid = $_SESSION['api']['id'];
        $user_id = $_SESSION['api']['user_id'];
        $orderData = ['create_time' => getTime() , 'good_id' => $param['id'] ,'user_id' => $user_id , 'uid' => $uid];
        if ($param['type'] == 2) {
            // 会员商品
            $vip_time = getVipTime($uid, $param['vip_time']);
            $res = Db::name('user')->where(['id' => $uid])->update(['vip_time' => date('Y-m-d H:i:s', $vip_time)]);
            if ($res) {
                // 减少对应用户的积分
                Db::name('user')->where(['id' =>  $uid])->update(['score' => $param['beLeftOver']]);
                $orderData['content'] = "vip时长 ： < $good_name > ，已发放到你的账户 !" ;
            }else error();
        } else if ($param['type'] == 3) {
            // 卡密商品
            $fake =  Db::name('fake')->where(['adder_user_id' => $user_id, 'type' => $param['type'], 'status' => 0])->find();
            if ($fake) {
                // 减少对应用户的积分
                Db::name('user')->where(['id' =>  $uid])->update(['score' => $param['beLeftOver']]);
                $orderData['content'] = "卡密商品 ：< $good_name > ：" . $fake['fake'];
            } else error('当前卡密库存不足');
            Db::name('fake')->where(['id' => $fake['id']])->update(['status' => 2]);
        }
        // 减少商品库存
        Db::name('good')->where(['id' =>  $param['id']])->update(['stock' => --$param['stock'] , 'buy_num' => ++$param['buy_num']]);
        // 插入商品订单表
        Db::name('good_order')->insert($orderData);
        success();
    }
}
